package com.mes.cloud.base.jwt;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt token相关操作
 *
 * @author: wxm
 * @date: 2019/5/2 17:59
 * @version: 1.0
 */
public class JwtUtil {

    /*过期时间*/
    private static final long EXPIRE_TIME = 15*60*1000;

    /*token私钥*/
    private static final String TOKEN_SECRET = "DFSDFSFSFSFSFS";

    /**
     * 生成签名 15min过期
     * @author: wxm
     * @date:   2019/5/2 18:01 
     * @param:  
     * @return: 加密token
     */
    public static String sign(String userName,String userId) throws UnsupportedEncodingException {
        //过期时间
        Date date = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        //私钥及加密算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map) // header
                .withClaim("loginName", userName)
                .withClaim("userId", userId)
                .withExpiresAt(date) // expire time
                .sign(algorithm); // signature
        return token;
    }

    /**
     * 校验token是否正确
     * @author: wxm
     * @date:   2019/5/2 18:27 
     * @param:  
     * @return:
     */
    public static boolean verify(String token) throws UnsupportedEncodingException {
        try {
             Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
             JWTVerifier verifier = JWT.require(algorithm).build();
             DecodedJWT jwt = verifier.verify(token);
             return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    public static void main (String[] args) throws UnsupportedEncodingException {
//        String token = sign("wxm", "P0119553");
//        System.out.println(token);

        boolean isTrue = verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbk5hbWUiOiJ3eG0iLCJleHAiOjE1NTY3OTQ0MzMsInVzZXJJZCI6IlAwMTE5NTUzIn0.7L47-wVXo6AYs6W5prEuaZNh4BpBk1kA_aPgOskg57M");
        System.out.println(isTrue);
    }
}
